﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Transactions;
using System.Data;

namespace Sohar.Core
{
	public class Word
	{
		public Word(string value, params WordMeaning[] meanings)
		{
			this.Value = value;
			this.Meanings = meanings;
		}

		public WordMeaning[] Meanings
		{
			get;
			set;
		}

		public string Value
		{
			get;
			set;
		}

		public void Save()
		{
			using (TransactionScope scope = new TransactionScope())
			{
				SoharGateway gateway = new SoharGateway();
				int wordID = gateway.InsertWord(this.Value);
				foreach (WordMeaning meaning in this.Meanings)
					meaning.Save(wordID);

				scope.Complete();
			}
		}

		public static Word[] GetAll()
		{
			return Get(null);
		}

		//public static Word[] GetByTags(params WordTag[] tags)
		//{
		//    return Get(null);
		//}

		public static Word[] Get(string wordPart)
		{
			List<Word> words = new List<Word>();
			SoharGateway gateway = new SoharGateway();
			using (IDataReader reader = gateway.GetWord(wordPart))
			{
				while (reader.Read())
					words.Add(new Word((string)reader["Value"], WordMeaning.GetByWord((int)reader["ID"])));
			}
			return words.ToArray();
		}

		public static Word GetFirst(string wordPart)
		{
			return Get(wordPart).First();
		}
	}
}
